<?php

class Utils extends Engine {

	public static $TIMER = 0;

	public static function getRandomString($len = 10, $type = 'ALNUM') {
		$alpha = array('a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z');
		$ALPHA = array('A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L', 'M', 'N', 'O', 'P', 'Q', 'R', 'S', 'T', 'U', 'V', 'W', 'X', 'Y', 'Z');
		$COLOR = array('A', 'B', 'C', 'D', 'E', 'F');
		$num = array('1', '2', '3', '4', '5', '6', '7', '8', '9', '0');
		$keyVals = array();
		$key = array();
		switch ($type) {
			case 'lower' :
				$keyVals = $alpha;
				break;
			case 'upper' :
				$keyVals = $ALPHA;
				break;
			case 'numeric' :
				$keyVals = $num;
				break;
			case 'ALPHA' :
				$keyVals = array_merge($alpha, $ALPHA);
				break;
			case 'alnum' :
				$keyVals = array_merge($alpha, $num);
				break;
			case 'ALNUM' :
				$keyVals = array_merge($ALPHA, $num);
				break;
			case 'COLOR' :
				$keyVals = array_merge($COLOR, $num);
				break;
		}
		for ($i = 0; $i <= $len - 1; $i++) {
			$r = rand(0, count($keyVals) - 1);
			$key[$i] = $keyVals[$r];
		}
		return join("", $key);
	}

	public static function createThumb($name, $newname, $new_w, $ext, $transparency = true) {
		$return = false;
		$img = false;
		if ($ext == ".jpeg" || $ext == ".jpg") {
			$img = @imagecreatefromjpeg($name);
		} elseif ($ext == ".png") {
			$img = @imagecreatefrompng($name);
		} elseif ($ext == ".gif") {
			$img = @imagecreatefromgif($name);
		}
		if (!$img) {
			return $return;
		}
		$old_x = imagesx($img);
		$old_y = imagesy($img);
		if ($old_x < $new_w) {
			$thumb_w = $old_x;
			$thumb_h = $old_y;
		} else {
			$thumb_w = $new_w;
			$thumb_h = floor(($old_y * ($new_w / $old_x)));
		}
		$thumb_w = ($thumb_w < 1) ? 10 : $thumb_w;
		$thumb_h = ($thumb_h < 1) ? 10 : $thumb_h;
		$new_img = imagecreatetruecolor($thumb_w, $thumb_h);

		if ($transparency) {
			if ($ext == ".png") {
				imagealphablending($new_img, false);
				$colorTransparent = imagecolorallocatealpha($new_img, 0, 0, 0, 127);
				imagefill($new_img, 0, 0, $colorTransparent);
				imagesavealpha($new_img, true);
			} elseif ($ext == ".gif") {
				$trnprt_indx = imagecolortransparent($img);
				if ($trnprt_indx >= 0) {
					//its transparent
					$trnprt_color = imagecolorsforindex($img, $trnprt_indx);
					$trnprt_indx = imagecolorallocate($new_img, $trnprt_color['red'], $trnprt_color['green'], $trnprt_color['blue']);
					imagefill($new_img, 0, 0, $trnprt_indx);
					imagecolortransparent($new_img, $trnprt_indx);
				}
			}
		} else {
			imagefill($new_img, 0, 0, imagecolorallocate($new_img, 255, 255, 255));
		}
		imagecopyresampled($new_img, $img, 0, 0, 0, 0, $thumb_w, $thumb_h, $old_x, $old_y);

		if ($ext == ".jpeg" || $ext == ".jpg") {
			imagejpeg($new_img, $newname);
			$return = true;
		} elseif ($ext == ".png") {
			imagepng($new_img, $newname);
			$return = true;
		} elseif ($ext == ".gif") {
			imagegif($new_img, $newname);
			$return = true;
		}
		imagedestroy($new_img);
		imagedestroy($img);
		return $return;
	}

	public static function formatDateUser($date, $includeTime = true) {
		if (!is_numeric($date)) {
			if ($includeTime) {
				return date(conf('DATE_TIME_FORMAT_USER'), strtotime($date));
			} else {
				return date(conf('DATE_FORMAT_USER'), strtotime($date));
			}
		} else {
			if ($includeTime) {
				return date(conf('DATE_TIME_FORMAT_USER'), $date);
			} else {
				return date(conf('DATE_FORMAT_USER'), $date);
			}
		}
	}

	public static function formatDateDb($date, $includeTime = true) {
		if (!is_numeric($date)) {
			if ($includeTime) {
				return date(conf('DATE_TIME_FORMAT_DB'), strtotime($date));
			} else {
				return date(conf('DATE_FORMAT_DB'), strtotime($date));
			}
		} else {
			if ($includeTime) {
				return date(conf('DATE_TIME_FORMAT_DB'), $date);
			} else {
				return date(conf('DATE_FORMAT_DB'), $date);
			}
		}
	}

	/**
	 * Formats a number. If the $amount is an integer number it will simply return the same number.
	 * If the $amount is float it will return the formatted number with $precision digits after coma.
	 * The $inf parameter tells whether to return or not the infinity sign (∞) in case the $amount is 0.
	 *
	 * @param int $amount
	 * @param int $precision
	 * @param bool $inf
	 * @return float|int|string
	 */
	public static function formatNumber($amount = 0, $precision = 2, $inf = false) {
		if (is_int($amount) && $amount > 0) {
			return $amount;
		} else if (is_float($amount) && $amount > 0) {
			return round($amount, $precision);
		} else {
			if ($inf) {
				return '&#8734;'; // Infinity sign ∞
			} else {
				return (int)$amount;
			}
		}
	}

	/**
	 * @static
	 * @param int $amount
	 * @param string $currencyType
	 * @return string
	 */
	public static function formatCurrency($amount = 0, $currencyType = MONETARY_FORMAT_DE_EURO) {
		return money_format($currencyType, $amount);
	}

	public static function startTimer() {
		self::$TIMER = microtime(true);
	}

	public static function endTimer() {
		return sprintf('%0.15f', microtime(true) - self::$TIMER);
	}

	/**
	 * Display an message to the user. Second argument indicates if there is an error or not
	 *
	 * @param string $mess
	 * @param boolean $error
	 * @return string
	 */
	public static function showMessage($mess="", $error = false) {
		if (!empty($mess)) {
			$args = func_get_args();
			array_shift($args);
			array_shift($args);
			if (isset($args[0]) && is_array($args[0])){
				$args = array_shift($args);
			}
			$mess = vsprintf($mess, $args);
			self::$TPL->assign('showMessageError', $error);
			self::$TPL->assign('showMessageString', $mess);
			return self::$TPL->display('message', true);
		} else {
			return "";
		}
	}

	/**
	 * Verify if there is $_POST
	 * @return boolean
	 */
	public static function isPost() {
		return ($_SERVER['REQUEST_METHOD'] == 'POST');
	}

	/**
	 * Verify if there is $_GET
	 * @return boolean
	 */
	public static function isGet() {
		return ($_SERVER['REQUEST_METHOD'] == 'GET');
	}

	public static function formatString($string = '') {
		if (!empty($string)) {
			return htmlspecialchars($string, ENT_QUOTES, 'UTF-8', false);
		} else {
			return null;
		}
	}

	public static function secureString ($str, $ignoreStripTags) {
		if ((!$ignoreStripTags) && is_string($str)) {
			return trim(strip_tags($str));
		} else {
			return $str;
		}
	}

	public static function secureArray($array, $ignoreStripTags) {
		if (!$ignoreStripTags) {
			$stripped_data = array();
			foreach ($array as $key => $value) {
				if (is_array($value)) {
					$stripped_data[self::secureString($key, $ignoreStripTags)] = self::secureArray($value, $ignoreStripTags);
				} else {
					$stripped_data[self::secureString($key, $ignoreStripTags)] = self::secureString($value, $ignoreStripTags);
				}
			}
		} else {
			$stripped_data = $array;
		}
		return $stripped_data;
	}

	public static function getGet($getKey = '', $type = 'any', $ignoreStripTags = false) {
		if(!isset($_GET[$getKey]) && $type != 'array') {
			return NULL;
		}
		if ($type == 'any') {
			return self::secureString($_GET[$getKey], $ignoreStripTags);

		} else if ($type == 'int' || $type == 'integer') {
			return (int)$_GET[$getKey];
		} else if ($type == 'float') {
			return (float)$_GET[$getKey];
		} else if ($type == 'str' || $type == 'string') {
			return self::secureString($_GET[$getKey], $ignoreStripTags);
		} else if ($type == 'array') {
			if (!isset($_GET[$getKey]) || !is_array($_GET[$getKey])) {
				if (!isset($_GET[$getKey])) {
					return array();
				}
				return (array)self::secureString($_GET[$getKey], $ignoreStripTags);
			} else {
				return self::secureArray($_GET[$getKey], $ignoreStripTags);
			}
		} else if ($type == 'bool' || $type == 'boolean') {
			return (bool)$_GET[$getKey];
		} else {
			return self::secureString($_GET[$getKey], $ignoreStripTags);
		}
	}

	public static function getPost($postKey = '', $type = 'any', $ignoreStripTags = false) {
		if(!isset($_POST[$postKey]) && $type != 'array') {
			return NULL;
		}

		if ($type == 'any') {
			return self::secureString($_POST[$postKey], $ignoreStripTags);
		} else if ($type == 'int' || $type == 'integer') {
			return (int)$_POST[$postKey];
		} else if ($type == 'float') {
			return (float)$_POST[$postKey];
		} else if ($type == 'str' || $type == 'string') {
			return self::secureString($_POST[$postKey], $ignoreStripTags);
		} else if ($type == 'array') {
			if (!isset($_POST[$postKey]) || !is_array($_POST[$postKey])) {
				if (!isset($_POST[$postKey])) {
					return array();
				}
				return (array)self::secureString($_POST[$postKey], $ignoreStripTags);
			} else {
				return self::secureArray($_POST[$postKey], $ignoreStripTags);
			}
		} else if ($type == 'bool' || $type == 'boolean') {
			return (bool)$_POST[$postKey];
		} else {
			return self::secureString($_POST[$postKey], $ignoreStripTags);
		}
	}

	public static function getCookie($cookieKey = '', $type = 'any', $ignoreStripTags = false) {
		if(!isset($_COOKIE[$cookieKey]) && $type != 'array') {
			return NULL;
		}

		if ($type == 'any') {
			return self::secureString($_COOKIE[$cookieKey], $ignoreStripTags);
		} else if ($type == 'int' || $type == 'integer') {
			return (int)$_COOKIE[$cookieKey];
		} else if ($type == 'float') {
			return (float)$_COOKIE[$cookieKey];
		} else if ($type == 'str' || $type == 'string') {
			return self::secureString($_COOKIE[$cookieKey], $ignoreStripTags);
		} else if ($type == 'array') {
			if (!isset($_COOKIE[$cookieKey]) || !is_array($_COOKIE[$cookieKey])) {
				if (!isset($_COOKIE[$cookieKey])) {
					return array();
				}
				return (array)self::secureString($_COOKIE[$cookieKey], $ignoreStripTags);
			} else {
				return self::secureArray($_COOKIE[$cookieKey], $ignoreStripTags);
			}
		} else if ($type == 'bool' || $type == 'boolean') {
			return (bool)$_COOKIE[$cookieKey];
		} else {
			return self::secureString($_COOKIE[$cookieKey], $ignoreStripTags);
		}
	}

	/**
	 * Redirect user to specified URL, if there is no argument, refresh page
	 *
	 * @param mixed $url URL if given
	 * @param bool $removeQuery
	 */
	public static function redirectTo($url=false, $removeQuery = false) {
		if (!$url) {
			$url = $_SERVER['REQUEST_URI'];
			if ($removeQuery) {
				$url = preg_replace('/\?.*/', '', $url);
			}
		}
		header('Location: '.$url);
		exit(0);
	}

    public static function getCurrentPageURL($queryString = true) {
        $pageURL = 'http';
        if (isset($_SERVER["HTTPS"]) && $_SERVER["HTTPS"] == "on") {$pageURL .= "s";}
        $pageURL .= "://";
        if ($_SERVER["SERVER_PORT"] != "80") {
            $pageURL .= $_SERVER["SERVER_NAME"].":".$_SERVER["SERVER_PORT"].$_SERVER["REQUEST_URI"];
        } else {
            $pageURL .= $_SERVER["SERVER_NAME"].$_SERVER["REQUEST_URI"];
        }
		if(!$queryString) {
			$pageURL = str_replace('?'.$_SERVER['QUERY_STRING'],'',$pageURL);
		}

        return $pageURL;
    }


	/**
	 * @static
	 * @param $array
	 * @param bool $xml
	 * @return mixed xml content
	 */
	public static function arrayToXml($array, $xml = false) {
		if($xml === false){
			$xml = new SimpleXMLElement('<root/>');
		}
		foreach($array as $key => $value){
			if(is_array($value)){
				self::arrayToXml($value, $xml->addChild($key));
			}else{
				$xml->addChild($key, $value);
			}
		}
		return $xml->asXML();
	}

    /**
     * Remove a folder recursively
	 * @static
	 * @param $dir
	 */
    public static function rRmDir($dir) {
        foreach(glob($dir . '/*') as $file) {
            if(is_dir($file))
                Utils::rRmDir($file);
            else
                unlink($file);
        }
        rmdir($dir);
    }

	/**
		 * Get an array and define all items as constants
		 * Used on set the user rights
		 *
		 * @param array $array
		 */
	public static function defineArray($array) {
		if (is_array($array) && count($array) > 0) {
			foreach($array as $key => $value) {
				if(!defined(strtoupper($key))) {
					define(strtoupper($key), $value);
				}
			}
		}
	}

	/**
	 * @static
	 * @param array $allColumns
	 * @param array $searchColumns
	 * @param bool $DBClass
	 * @param bool $getTotalFunction
	 * @return array|bool
	 * this function returns searchQuery, OrderBy and limit query for use search and ordering for dataTable tables (ajax)
	 */
	public static function getSqlQueriesForPagination($allColumns=array(), $searchColumns = array(), $DBClass = false, $getTotalFunction = false) {
		if(count($allColumns) == 0 || count($searchColumns) == 0) {
			return array(false,false);
		}
		$orderingRules = array();
		if (post('iSortCol_0') !== null) {
			$sortingCols = post('iSortingCols', 'int');
			for ($i = 0; $i < $sortingCols; $i++) {
				if (post('bSortable_' . post('iSortCol_' . $i, 'int')) == 'true' && in_array($allColumns[post('iSortCol_' . $i, 'int')], $searchColumns)) {
					$orderingRules[] = "`" . $allColumns[post('iSortCol_' . $i, 'int')] . "` " . self::$DB->escapeString(post('sSortDir_' . $i));
				}
			}
		}

		if (!empty($orderingRules)) {
			$orderBy = " ORDER BY ".implode(", ", $orderingRules);
		} else {
			$orderBy = "";
		}

		// Array with search queries
		$searchQueries = array();
		// Search logic for all fields
		$generalSearchString = post('sSearch');
		if (!empty($generalSearchString)) {
			$filteringRules = array();
			$i = 0;
			foreach ($allColumns as $column) {
				if (post('bSearchable_'.$i) == 'true' && in_array($column, $searchColumns)) {
					$filteringRules[] = "`" . $column . "` LIKE " . self::$DB->escapeValue('%' . str_replace('%', "\\%", $generalSearchString) . '%');
				}
				$i++;
			}
			$searchQueries[] = '('.implode(" OR ", $filteringRules).')';
		}
		// Search logic for individual fields
		$filteringRules = array();
		$i = 0;
		foreach ($allColumns as $column) {
			if (post('bSearchable_' . $i) == 'true' && in_array($column, $searchColumns) && strlen(post('sSearch_' . $i, 'string')) > 0) {
				$filteringRules[] = "`" . $column . "` LIKE " . self::$DB->escapeValue('%' . str_replace('%', "\\%", post('sSearch_' . $i, 'string')) . '%');
			}
			$i++;
		}
		if (count($filteringRules) > 0) {
			$searchQueries[] = '('.implode(" AND ", $filteringRules).')';
		}

		$limit = '';
		if (post('iDisplayLength', 'int') > 0) {
			$limit = "LIMIT ".post('iDisplayStart', 'int').', '.post('iDisplayLength', 'int');
		}
		// Combining all filtering rules together
		if (!empty($searchQueries)) {
			$searchQuery = implode(" AND ", $searchQueries);
		} else {
			$searchQuery = "";
		}

		/* the class name and the method name are dynamic! */
		if($DBClass && $getTotalFunction){
			$totalElements = $DBClass::$getTotalFunction();
			$totalFilteredElements = $DBClass::$getTotalFunction($searchQuery);
			self::$TPL->assign('totalElements', $totalElements);
			self::$TPL->assign('totalFilteredElements', $totalFilteredElements);
		}

		return array($searchQuery, $orderBy, $limit);
	}

	/**
	 * @static
	 * @param $dir
	 * @param int $rights
	 */
	public static function mkDirIfNotExist($dir,$rights = 0775){
		if(!is_dir($dir)){
			mkdir($dir, $rights, true);
		}
	}

	public static function getCurrentUrl() {
		return (isset($_SERVER['HTTP_HOST']) ? (isset($_SERVER['HTTPS']) ? 'https://' : 'http://').$_SERVER['HTTP_HOST'].$_SERVER['REQUEST_URI'] : false);
	}


	/**
	 * Handles file uploads.
	 * @static
	 * @param array $arrayFile  if file is not from post, you have to add to array, key  = "exists" with value true
	 * @param $path
	 * @param $id
	 * @param array $allowedExtensions
	 * @param bool $saveOriginalName
	 * @param int $fileSizeLimit
	 * @param bool $inGallery
	 * @param int $galleryId
	 * @return array
	 */
	public static function uploadFile($arrayFile=array(), $path, $id, $allowedExtensions, $saveOriginalName = false, $fileSizeLimit = 0, $inGallery = true, $galleryId = 0){
		if (count($arrayFile) == 0 || empty($path) || empty($id) || count($allowedExtensions) == 0) {
			return array(
				'error' => true,
				'message' => t(T_ERROR_MESSAGE, 'wrong_arguments'),
			);
		}

		$fileInfo = array();
		if (!isset($arrayFile['tmp_name'])) {
			if (isset($arrayFile[0]) && isset($arrayFile[1])) {
				$fileInfo['first'] = $arrayFile[0];
				$fileInfo['second'] = $arrayFile[1];
			} else {
				return array(
					'error' => true,
					'message' => t(T_ERROR_MESSAGE, 'wrong_arguments')
				);
			}
		} else {
			$fileInfo['first'] = $arrayFile;
		}

		$constantPath = false;
		if ($saveOriginalName) {
			$name = $fileInfo['first']['name'];
		} else {
			if (isset($fileInfo['second'])) {
				$constantPath = true;
				$name = $id . '_' . str_replace('.', '', microtime(true));
			} else {
				$name =  md5($fileInfo['first']['name'] . microtime());
			}
		}

		if ($fileSizeLimit > 0) {
			$sizeFirst = filesize($fileInfo['first']['tmp_name']);
			$sizeSecond = 0;
			if (isset($fileInfo['second'])) {
				$sizeSecond = filesize($fileInfo['second']['tmp_name']);
			}
			if ($sizeFirst > $fileSizeLimit || $sizeSecond > $fileSizeLimit) {
				return array(
					'error' => true,
					'message' => t(T_ERROR_MESSAGE, 'error_file_size')
				);
			}
		}

		if (isset($fileInfo['first']['exists'])) {
			$fileFirst = pathinfo($fileInfo['first']['tmp_name']);
			if (rename($fileInfo['first']['tmp_name'], $path . $name . '.' . $fileFirst['extension'])) {
				return array(
					'error' => false,
					'message' => t(T_MESSAGE_RESULT, 'upload_success'),
					'data' => array(
						'path' => str_replace(PUBLIC_RESOURCES_PATH,'',$path),
						'name' => $name . '.' . $fileFirst['extension']
					)
				);
			} else {
				return array(
					'error' => true,
					'message' => t(T_ERROR_MESSAGE, 'error_upload')
				);
			}

		//Photo for products upload case
		} else if(isset($arrayFile['photoId'])) {
			$photoId = $arrayFile['photoId'] ? $arrayFile['photoId'] : null;
			$photosObj = new Db_Products_Photos($photoId);
			$photosObj->id = $photoId;
			$photosObj->ph_gallery_id = ($constantPath) ? $galleryId : $id;
			$pathName = ($constantPath) ? $path . $id . DS : $path . date('Y-m',time()) . DS . $id . DS;
			if (PHP_FILE_NOT_UPLOADED_ERROR != $fileInfo['first']['error']) {
				$fileFirst = pathinfo($fileInfo['first']['name']);
				Utils::mkDirIfNotExist($pathName);
				if (!in_array($fileFirst['extension'], $allowedExtensions)) {
					return array(
						'error' => true,
						'message' => t(T_ERROR_MESSAGE, 'wrong_extension')
					);
				}
				$pathNameImage = $pathName. $name . '.' . $fileFirst['extension'];
				if (move_uploaded_file($fileInfo['first']['tmp_name'],$pathNameImage )) {
					$imageSize = getimagesize($pathNameImage);

					$photosObj->ph_original = $fileInfo['first']['name'];
					$photosObj->ph_name = $name . '.' . $fileFirst['extension'];
					$photosObj->ph_path = str_replace(PUBLIC_RESOURCES_PATH,'',$pathName);
					$photosObj->ph_ow = $imageSize[0];
					$photosObj->ph_oh = $imageSize[1];
				} else {
					return array(
						'error' => true,
						'message' => t(T_ERROR_MESSAGE, 'error_upload')
					);
				}
			}

			if (PHP_FILE_NOT_UPLOADED_ERROR != $fileInfo['second']['error']) {
				$fileSecond = pathinfo($fileInfo['second']['name']);
				$resizeName = 'th_' . $name;
				$resizeNameFull = $resizeName . '.' . $fileSecond['extension'];
				$pathNameImage = $pathName. $resizeNameFull;
				if (!in_array($fileSecond['extension'], $allowedExtensions)) {
					return array(
						'error' => true,
						'message' => t(T_ERROR_MESSAGE, 'wrong_extension')
					);
				}
				if (move_uploaded_file($fileInfo['second']['tmp_name'], $pathNameImage)) {
					$imageResSize = getimagesize($pathNameImage);
					$photosObj->ph_resized = $resizeNameFull;
					$photosObj->ph_rw = $imageResSize[0];
					$photosObj->ph_rh = $imageResSize[1];
				} else {
					return array(
						'error' => true,
						'message' => t(T_ERROR_MESSAGE, 'error_upload')
					);
				}
			}
			$photosObj->save();
			$dataReturn = array(
				'ph_id' => $photosObj->id
			);

			return array(
				'error' => false,
				'message' => t(T_MESSAGE_RESULT, 'upload_success'),
				'data' => $dataReturn
			);
		} else {

			$fileFirst = pathinfo($fileInfo['first']['name']);

			$pathName = ($constantPath) ? $path . $id . DS : $path . date('Y-m',time()) . DS . $id . DS;
			Utils::mkDirIfNotExist($pathName);

			$pathNameImage = $pathName. $name . '.' . $fileFirst['extension'];

			if (in_array($fileFirst['extension'], $allowedExtensions)) {
				if (isset($fileInfo['second'])) {
					$fileSecond = pathinfo($fileInfo['second']['name']);
					if (!in_array($fileSecond['extension'], $allowedExtensions)) {
						return array(
							'error' => true,
							'message' => t(T_ERROR_MESSAGE, 'wrong_extension')
						);
					}
				}
				if (move_uploaded_file($fileInfo['first']['tmp_name'],$pathNameImage )) {
					if ($inGallery) {

						$imageSize = getimagesize($pathNameImage);
						$imageResSize = array();
						//we have 2 cases:
						//1.File is uploaded from flash
						//2.Files is uploaded from products interface

						//1
						$resizeName = 'th_' . $name;
						$resizeNameFull = '';
						if (!isset($fileInfo['second'])) {

							if ($fileFirst['extension'] != 'swf') {
								$image = new Imagick($pathNameImage);
								if ($imageSize[0] > 500) {
									$image->thumbnailImage(500, 0);
								} elseif ($imageSize[1] > 500) {
									$image->thumbnailImage(0, 500);
								}
								$resizeNameFull = $resizeName . '.' . $fileFirst['extension'];
								$image->writeImage($pathName . $resizeNameFull);
								$imageResSize =  getimagesize($pathName . $resizeNameFull);
								$image->clear();
								$image->destroy();
							}

						} else {
							//2
							$fileSecond = pathinfo($fileInfo['second']['name']);
							$resizeNameFull = $resizeName . '.' . $fileSecond['extension'];
							$pathNameImage = $pathName. $resizeNameFull;
							if (move_uploaded_file($fileInfo['second']['tmp_name'], $pathNameImage)) {
								$imageResSize = getimagesize($pathNameImage);
							} else {
								return array(
									'error' => true,
									'message' => t(T_ERROR_MESSAGE, 'error_upload')
								);
							}
						}

						$photosObj = new Db_Products_Photos();
						$photosObj->id = null;
						$photosObj->ph_gallery_id = ($constantPath) ? $galleryId : $id;
						$photosObj->ph_original = $fileInfo['first']['name'];
						$photosObj->ph_name = $name . '.' . $fileFirst['extension'];
						$photosObj->ph_path = str_replace(PUBLIC_RESOURCES_PATH,'',$pathName);
						$photosObj->ph_ow = $imageSize[0];
						$photosObj->ph_oh = $imageSize[1];
						$photosObj->ph_resized = $resizeNameFull;
						$photosObj->ph_rw = $imageResSize[0];
						$photosObj->ph_rh = $imageResSize[1];
						$photosObj->save();

						$dataReturn = array(
							'ph_id' => $photosObj->id,
							'ph_original' => $name . '.' . $fileFirst['extension'],
							'ph_resized' => $resizeNameFull,
							'ph_path' => str_replace(PUBLIC_RESOURCES_PATH,'',$pathName),
							'ph_gallery_id' => $id,
							'ph_ow' => $imageSize[0],
							'ph_oh' => $imageSize[1],
							'ph_rw' => $imageResSize[0],
							'ph_rh' => $imageResSize[1]
						);

						return array(
							'error' => false,
							'message' => t(T_MESSAGE_RESULT, 'upload_success'),
							'data' => $dataReturn
						);

					} else {
						return array(
							'error' => false,
							'message' => t(T_MESSAGE_RESULT, 'upload_success'),
							'data' => array('path'=> str_replace(PUBLIC_RESOURCES_PATH,'',$pathNameImage))
						);
					}
				} else {
					return array(
						'error' => true,
						'message' => t(T_ERROR_MESSAGE, 'error_upload')
					);
				}
			} else {
				return array(
					'error' => true,
					'message' => t(T_ERROR_MESSAGE, 'wrong_extension')
				);
			}
		}

	}


	/**
	 * @static
	 * @param $url
	 * @return mixed|string
	 */
	public static function filterUrl($url) {
		$url = strtr(strtolower(trim(strip_tags($url))), array('Ü' => 'ü', 'Ö' => 'ö', 'Ä' => 'ä', 'Á'=>'á', 'É'=>'é', 'Í'=>'í', 'Ñ'=>'ñ', 'Ó'=>'ó', 'Ú'=>'ú'));

        if ($url != '') {
            // German replacements
            $url = str_replace("ß", "ss", $url);
            $url = str_replace("ä", "ae", $url);
            $url = str_replace("ü", "ue", $url);
            $url = str_replace("ö", "oe", $url);
            //Spanish
            $url = str_replace("á", "a", $url);
            $url = str_replace("é", "e", $url);
            $url = str_replace("í", "i", $url);
            $url = str_replace("ñ", "n", $url);
            $url = str_replace("ó", "o", $url);
            $url = str_replace("ú", "u", $url);
            $url = str_replace("¡", "",  $url);
            $url = str_replace("¿", "",  $url);
             //Polish
            $url = str_replace("Ą", "A", $url);
            $url = str_replace("ą", "a", $url);
            $url = str_replace("Ę", "E", $url);
            $url = str_replace("ę", "e", $url);
            $url = str_replace("Ó", "O", $url);
            $url = str_replace("ó", "o", $url);
            $url = str_replace("Ć", "C", $url);
            $url = str_replace("ć", "c", $url);
            $url = str_replace("Ł", "L", $url);
            $url = str_replace("ł", "l", $url);
            $url = str_replace("Ń", "N", $url);
            $url = str_replace("ń", "n", $url);
            $url = str_replace("Ś", "S", $url);
            $url = str_replace("ś", "s", $url);
            $url = str_replace("Ź", "Z", $url);
            $url = str_replace("ź", "z", $url);
            $url = str_replace("Ż", "Z", $url);
            $url = str_replace("ż", "z", $url);
         }

        // convert to lowercase
        $url =strtolower($url);

        //replace single quotes and double quotes first
		$url = preg_replace('/[\']/i', '', $url);
		$url = preg_replace('/["]/i', '', $url);

		$url = preg_replace('/&/', 'and', $url);

		//remove non-valid characters
		$url = preg_replace('/[^-a-z0-9ßäüö.]/i', '-', $url);
		$url = preg_replace('/-[-]*/i', '-', $url);

		//remove from beginning and end
		$url = preg_replace('/' . '-' . '$/i', '', $url);
		$url = preg_replace('/^' . '-' . '/i', '', $url);

          // 	print $url . '-'; die;

         return $url;
	}

	/**
	 * Generates sitemap both in HTML and XML. You can control the output type with the $xml parameters
	 * @param string $projectIdentifier A project identifier
	 * @param string $projectCountryId The country id to look for in DB
	 * @param bool $xml True to return XML, false for HTML
	 * @return string Raw XML or HTML, depending on the function argument
	 */
	public static function generateSiteMap($projectIdentifier, $projectCountryId, $xml = false) {
		$siteMapPages = Db_Cms_Pages::getPagesForSitemap($projectIdentifier);
		$project = Db_Projects::findByFields( array(
			'pr_country_id' => $projectCountryId,
			'pr_identifier' => $projectIdentifier
		));
		if (!$project) {
			return false;
		}
		$sitemapUrls = array();
		foreach ($siteMapPages as $page) {
			if ($page['p_dynamic_url']) {
				$paginations = false;
				if ('product' == $page['p_pagination_type'] && $xml) {
					$paginations = Db_Cms_PagePagination::getProductsUrlsByPageId($projectIdentifier, $page['page_id']);
				} else if (in_array($page['p_pagination_type'], array('category', 'poems'))) {
					/*$sitemapUrls[] =  array(
						'href' => $project->pr_domain_live . $page['p_url'],
						'title' => $page['p_title']
					);*/
					$paginations = Db_Cms_Pages::getPaginationUrlsByPage($page);
				}
				if ($paginations) {
					foreach ($paginations as $pagination) {
						$sitemapUrls[] = array(
							'href' => $project->pr_domain_live . $pagination['pp_page_url'],
							'title' => (isset($pagination['pp_page_title']) ? $pagination['pp_page_title'] : '')
						);
					}
				}
			} else {
				$sitemapUrls[] = array(
					'href' => $project->pr_domain_live . $page['p_url'],
					'title' => $page['p_title']
				);
			}
		};
		self::$TPL->assign('sitemapUrls', $sitemapUrls);
		if ($xml) {
			return self::$TPL->display('xml_sitemap', true);
		} else {
			return self::$TPL->display('sitemap', true);
		}
	}

	/**
	 * @static
	 * @param $memoryProductId
	 * @return string
	 */
	public static function memoryProductIdEncode($memoryProductId) {

		$firstString = FIRST_ENCRYPT_STRING;
		$secondString = SECOND_ENCRYPT_STRING;

		$memoryProductId = strval($memoryProductId);

		$encodedString = '';

		for ($i = 0; $i < strlen($memoryProductId); $i++) {
			$encodedString .= $firstString[$memoryProductId[$i]].$secondString[$memoryProductId[$i]];
		}
		return $encodedString;
	}

	/**
	 * @static
	 * @param $memoryProductIdEncoded
	 * @return int
	 */
	public static function memoryProductIdDecode($memoryProductIdEncoded) {

		$firstString = FIRST_ENCRYPT_STRING;
		$memoryProductId = '';

		for($i = 0; $i < strlen($memoryProductIdEncoded) / 2; $i++) {
			$memoryProductId .= strpos($firstString, $memoryProductIdEncoded[$i*2]);
		}

		return intval($memoryProductId);
	}


	/**
	 * @static
	 * @param bool $addDefaultReply
	 * @param bool $newConnection
	 */
	public static function instantiateMail($addDefaultReply = true, $newConnection = false) {
		if (!self::$MAIL || $newConnection) {
			self::$MAIL = new PHPMailer();
			self::$MAIL->IsSMTP();
			self::$MAIL->CharSet = 'UTF-8';
			/*self::$MAIL->Host = self::$GlobalVariables['email_host'];
			if(strpos(self::$GlobalVariables['email_host'], 'mail.') !== false){
				self::$MAIL->SMTPSecure = 'tls';
			}
			self::$MAIL->SMTPAuth = true;
			self::$MAIL->Username = self::$GlobalVariables['email_username'];
			self::$MAIL->Password = self::$GlobalVariables['email_password'];

			self::$MAIL->SetFrom(self::$GlobalVariables['email_from'], self::$GlobalVariables['email_fromname']);
			if ($addDefaultReply) {
				self::$MAIL->AddReplyTo(self::$GlobalVariables['email_from'], self::$GlobalVariables['email_fromname']);
			}*/
			self::$MAIL->SMTPAuth = false;
			self::$MAIL->SetFrom(self::$SETTINGS["contact_email"], self::$SETTINGS["contact_email_title"]);
			if ($addDefaultReply) {
				self::$MAIL->AddReplyTo(self::$SETTINGS["contact_email"],self::$SETTINGS["contact_email_title"]);
			}
		} else {
			self::$MAIL->ClearAllRecipients();
			self::$MAIL->ClearAttachments();
			self::$MAIL->ContentType = 'text/plain';
			self::$MAIL->Body = '';
			self::$MAIL->AltBody = '';
		}
	}

}
